package com.example.javaproject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.Audio.Media;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Songs extends Activity {

	// 声明组件对象
	boolean isStop = com.example.javaproject.MainActivity.isStop;
	boolean flag;
	
	// 内容提供者
	ListView songsList;
	ImageView songsstop;
	ImageView songsstart;
	ImageView songspause;
	TextView singerMusic;
	int songsPosition;
	int currentPostion;

	ArrayList<String> songList; // 定义一个List集合，用于存储歌曲的名称
	ArrayList<String> pathList; // 定义一个List集合，用于存储歌曲的路径
	ArrayList<String> albumList;// 定义一个List集合，用于存储专辑的名称
	ArrayList<String> singerList;// 定义一个List集合，用于存储歌手的名字

	Uri uri = Media.EXTERNAL_CONTENT_URI; // 指定要访问的内容提供者的Uri
	ContentResolver cr;
	ArrayAdapter<String> adapter; // 数据适配器，用于加载数据给ListView
	MediaPlayer songsmp;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_songs);

		// 获取组件对象
		songsList = (ListView) findViewById(R.id.songsList);// 查找视图
		songsstop = (ImageView) findViewById(R.id.songsstop);
		songsstart = (ImageView) findViewById(R.id.songsstart);
		songspause = (ImageView) findViewById(R.id.songspause);
		singerMusic = (TextView) findViewById(R.id.singerMusic);

		// 对象实例化
		songList = new ArrayList<String>();
		pathList = new ArrayList<String>();
		albumList = new ArrayList<String>();
		singerList = new ArrayList<String>();

		cr = getContentResolver(); // 直接调用Activity类有的getContentResolver获取一个内容解析器实例
		songsmp = com.example.javaproject.MainActivity.albumMp;

		String[] columns = { Media.TITLE, Media.DATA, Media.ALBUM, Media.ARTIST };// {歌名，路径，专辑名，歌手名}

		Cursor c = cr.query(uri, columns, null, null, null);
		while (c.moveToNext()) {
			songList.add(c.getString(0)); // 将歌曲名称（第一列）加入到songList集合
			pathList.add(c.getString(1)); // 将该行第二列的路径加入到pathList集合
			albumList.add(c.getString(2));
			singerList.add(c.getString(3));
		}
		// 四个参数：上下文，ListView每个选项的样式Layout编号，具体样式视图编号，数据列表
		adapter = new ArrayAdapter<String>(Songs.this, R.layout.item,
				R.id.tvItem, songList);
		songsList.setAdapter(adapter);

		// 点击之前显示第一个音乐
		singerMusic.setText(songList.get(0));
		// 要处理ListView的选项点击事件
		songsList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// ---------------------------------------------------------------------------------------------
				PrintWriter pw = null;
				BufferedReader br = null;
				// 创建一个文件用于记录歌曲播放时间
				File file = new File(Environment.getExternalStorageDirectory()
						.toString() + "/" + songList.get(position) + ".txt");
				// 如果文件不存在，也就是第一次播放该歌曲
				try {

					if (!file.exists()) {
						// 初始化字符输出流
						pw = new PrintWriter(new FileOutputStream(file));
						// 设置初始播放次数为1
						pw.write("1");
						pw.flush();// 刷新缓冲区

					} else {
						// 文件存在，也就是以前播放过该歌曲

						// 用于读文件
						br = new BufferedReader(new FileReader(file));
						// 先读取以前的播放次数
						String count = br.readLine();

						// 用于写文件
						pw = new PrintWriter(new FileOutputStream(file));
						// 重新写入文件 设置新的播放次数为原来次数+1
						pw.println((Integer.parseInt(count) + 1) + "");
						pw.flush();// 刷新缓冲区

					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				// ---------------------------------------------------------------------------------------------

				songsPosition = position;
				com.example.javaproject.MainActivity.name = songList
						.get(position);
				singerMusic.setText(com.example.javaproject.MainActivity.name);
				try {
					songsmp.reset(); // 每次重置MediaPlayer，然后才能重新指定资源
					// 设置数据源，从pathList获取position位置的歌曲的路径
					songsmp.setDataSource(pathList.get(position));
					songsmp.prepare();
					songsmp.start();
					isStop = false;
				} catch (Exception e) {
					Log.e("MainActivity", e.getMessage());
				}
			}
		});

		// 设置监听器
		MyListener listener = new MyListener();
		songsstart.setOnClickListener(listener);
		songspause.setOnClickListener(listener);
		songsstop.setOnClickListener(listener);
		singerMusic.setOnClickListener(listener);
	}
	
	@Override
	protected void onResume(){
		super.onResume();
		singerMusic.setText(com.example.javaproject.MainActivity.name);
	}
	

	// 监听器
	class MyListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.songsstart:
				Toast t3 = Toast
						.makeText(Songs.this, "上一首", Toast.LENGTH_SHORT);
				t3.show();
				if (songsPosition >= 1 && songsPosition <= pathList.size()) {

					try {
						singerMusic.setText(songList.get(songsPosition - 1));
						songsmp.reset();
						songsmp.setDataSource(pathList.get(songsPosition - 1));
						songsPosition = songsPosition - 1;
						songsmp.prepare();
						songsmp.start();
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else {
					try {
						singerMusic.setText(songList.get(pathList.size() - 1));
						songsmp.reset();
						songsmp.setDataSource(pathList.get(pathList.size() - 1));
						songsPosition = pathList.size() - 1;
						songsmp.prepare();
						songsmp.start();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				break;
			case R.id.songspause:
				if (!isStop) {
					songspause.setImageDrawable(getResources().getDrawable(
							R.drawable.start));
					Toast t2 = Toast.makeText(Songs.this, "已暂停",
							Toast.LENGTH_SHORT);
					t2.show();
					songsmp.pause();
					isStop = true;
					flag=isStop;
				} else {
					songspause.setImageDrawable(getResources().getDrawable(
							R.drawable.pause));
					songsmp.start();
					Toast t1 = Toast.makeText(Songs.this, "播放",
							Toast.LENGTH_SHORT);
					t1.show();
					isStop = false;
					flag=isStop;
				}
				break;
			case R.id.songsstop:
				Toast t4 = Toast
						.makeText(Songs.this, "下一首", Toast.LENGTH_SHORT);
				t4.show();
				if (songsPosition >= 0 && songsPosition <= pathList.size() - 2) {

					try {
						singerMusic.setText(songList.get(songsPosition + 1));
						songsmp.reset();
						songsmp.setDataSource(pathList.get(songsPosition + 1));
						songsPosition = songsPosition + 1;
						songsmp.prepare();
						songsmp.start();
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else {
					try {
						singerMusic.setText(songList.get(0));
						songsmp.reset();
						songsmp.setDataSource(pathList.get(0));
						songsPosition = 0;
						songsmp.prepare();
						songsmp.start();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				break;
			case R.id.singerMusic:
				currentPostion = songsmp.getCurrentPosition();
				Intent individual1 = new Intent(Songs.this,
						IndividualSongs.class);
				individual1.putExtra("albumName", albumList.get(songsPosition));
				individual1.putExtra("songsName", songList.get(songsPosition));
				individual1.putExtra("singerName",
						singerList.get(songsPosition));
				individual1.putExtra("songsPath", pathList.get(songsPosition));
				individual1.putExtra("currentPostion", currentPostion);
				individual1.putExtra("flag",flag);
				startActivity(individual1);
			}
		}
	}

}
